package com.woniuxy.service.impl;

import com.woniuxy.mapper.TagsResidentRelationMapper;
import com.woniuxy.service.TagsResidentRelationService;
import com.woniuxy.util.ResponseEnum;
import com.woniuxy.util.ResponseUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 标签居民关系服务实现类
 * 实现标签居民关系相关的业务逻辑
 */
@Service
@Transactional
public class TagsResidentRelationServiceImpl implements TagsResidentRelationService {
    @Resource
    private TagsResidentRelationMapper mapper;
    /**
     * 更新居民的疾病标签
     * @param residentId 居民ID
     * @param newLabelIds 新的标签ID列表
     * @return 返回更新操作是否成功
     */
    @Override
    public Boolean updateResidentDiseaseLabels(Integer residentId, List<Integer> newLabelIds) {
        // 1. 查询该居民当前所有的疾病标签ID
        List<Integer> oldLabelIds = mapper.findLabelIdsByResidentId(residentId);

        // 2. 计算需要删除的ID (在旧的里面，但不在新的里面)
        List<Integer> idsToDelete = oldLabelIds.stream()
                .filter(oldId -> !newLabelIds.contains(oldId))
                .collect(Collectors.toList());

        // 3. 计算需要新增的ID (在新的里面，但不在旧的里面)
        List<Integer> idsToInsert = newLabelIds.stream()
                .filter(newId -> !oldLabelIds.contains(newId))
                .collect(Collectors.toList());

        Integer deleteResult = 0;
        // 4. 执行删除操作
        if (idsToDelete != null && !idsToDelete.isEmpty()) {
            deleteResult = mapper.batchDelete(residentId, idsToDelete);
        }
        Integer insertResult = 0;
        // 5. 执行新增操作
        if (idsToInsert != null && !idsToInsert.isEmpty()) {
            insertResult = mapper.batchInsert(residentId, idsToInsert);
        }
        return deleteResult > 0 && insertResult > 0
                ? true
                : false;
    }
}
